package queueDemo;
class MyQueue {
    private int capacity = 0xffff;
    private Integer[] elem ;//存储数组
    private int size;//存储元素个数
    private int head;//队头
    private int tail;//队尾

    public MyQueue() {
        elem = new Integer[capacity];
    }
    public MyQueue(int capacity) {
        this.capacity = capacity;
        elem = new Integer[capacity];
    }

    public void put(int key) throws InterruptedException {
        synchronized (this) {
            while (size == elem.length) {
                this.wait();
            }
            elem[tail] = key;
            tail = (tail + 1) % capacity;
            size++;
            this.notify();
        }
    }

        public int take() throws InterruptedException {
            synchronized (this) {
                while(size == 0) {
                    this.wait();
                }
                int ret = elem[head];
                head = (head + 1) % capacity;
                size--;
                this.notify();
                return ret;
            }
    }
}


public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        MyQueue myQueue = new MyQueue(5);
        myQueue.put(1);
        myQueue.put(2);
        myQueue.put(3);
        myQueue.put(4);
        while(true) {
            System.out.println(myQueue.take());
        }
    }
}
